import React, { useEffect, useState } from 'react';
import orgCtrl from '@/ts/controller';
import { IDirectory, IFile, ITarget } from '@/ts/core';
import OpenFileDialog from '@/components/OpenFileDialog';
import { message } from 'antd';
import { loadSettingMenu } from '@/components/OpenFileDialog/config';
import { MenuItemType } from 'typings/globelType';

const SelectFile: React.FC<{
  tagType: string;
  onChange: () => void;
  onCheck: (file: IFile | undefined) => void;
  pages: any[];
}> = ({ tagType, onChange, onCheck, pages }) => {
  const [content, setContent] = useState<IFile[]>([]);
  const [selectMenu, setSelectMenu] = useState<MenuItemType>();
  const [typeNames] = useState<string[]>(['单位']);

  useEffect(() => {
    setContent([orgCtrl.user, ...orgCtrl.user.companys]);
  }, []);

  useEffect(() => {
    if (selectMenu) {
      const contents: IFile[] = [];
      const dir = selectMenu.item as IDirectory;
      dir.target?.targets.forEach(async (a) => {
        if (['5', '6'].includes(tagType)) {
          contents.push(...(await a.directory.loadAllTemplate()));
        } else {
          contents.push(...(await a.directory.loadAllApplication()));
        }
      });
      setContent(contents);
    }
  }, [selectMenu]);
  return (
    <div className={`navigationBar`}>
      <OpenFileDialog
        title={`选择`}
        rightShow={false}
        fileContents={content}
        onSelectMenuChanged={(menu) => {
          setSelectMenu(menu);
        }}
        accepts={tagType == '5' ? ['页面模板'] : tagType == '6' ? ['商城模板'] : ['应用']}
        rootKey={''}
        showFile
        onLoadMenu={() => loadSettingMenu('', tagType == '6' || false, typeNames)}
        excludeIds={pages
          .map((item) => item.metadata.id)
          .filter((id: string) => !pages.includes(id))}
        onCancel={() => {
          onChange();
        }}
        onOk={(files) => {
          if (files && files.length > 0) {
            onCheck(files[0]);
          } else {
            message.info('请选择');
          }
        }}
      />
    </div>
  );
};
export default SelectFile;
